<template>
  <p-select
    class="default-select-container"
    :value="value"
    :placeholder="placeholder"
    :allow-clear="allowClear"
    :label-in-value="labelInValue"
    @change="handleChange"
  >
    <!-- 不要修改下面格式，有bug label 会加上空格 -->
    <!-- eslint-disable vue/singleline-html-element-content-newline -->
    <!-- prettier-ignore -->
    <p-select-option
      v-for="item in mergeOptions"
      :key="item.name"
      :value="item.uid"
    >{{ item.name }}</p-select-option>
  </p-select>
</template>

<script>
import { postDepcMgrInfo } from '@/api/public.js';
export default {
  props: {
    allowClear: {
      type: Boolean,
      default: true,
    },
    value: {
      type: [Number, String],
      default: '',
    },
    placeholder: {
      type: String,
      default: '请选择',
    },
    hasAll: {
      type: Boolean,
      default: true,
    },
    options: {
      type: Array,
      default: () => [],
    },
    parentId: {
      type: [String, Number],
      default: undefined,
    },
    labelInValue: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      codeOptions: [],
    };
  },
  computed: {
    mergeOptions() {
      return this.options.length ? this.options : this.codeOptions;
    },
  },
  watch: {
    parentId: {
      handler() {
        this.getDicList();
      },
      immediate: true,
    },
  },

  methods: {
    async getDicList() {
      if (this.options.length) return;
      const result = await postDepcMgrInfo({});
      const data = result?.data?.data || [];
      if (this.hasAll) {
        if (!data.length) return [];
        this.codeOptions = [...data];
      } else {
        this.codeOptions = data;
        if (!this.value) {
          if (this.labelInValue) {
            this.$emit(
              'input',
              { key: data[0]?.name || '', label: data[0]?.uid },
              true
            );
          } else {
            this.$emit('input', data[0]?.name || '', true);
          }
        }
      }
    },
    handleChange(value) {
      this.$emit('input', value);
    },
  },
};
</script>

<style lang="less" scoped>
.default-select-container {
  width: 100%;
}
</style>
